/*
 *    Copyright 2022 The DSMS Authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dsms.modules.rbd.task;

import cn.hutool.json.JSONUtil;
import com.ceph.rados.IoCTX;
import com.ceph.rados.Rados;
import com.ceph.rados.exceptions.ErrorCode;
import com.ceph.rbd.RbdException;
import com.ceph.rbd.RbdImage;
import com.dsms.common.constant.ResultCode;
import com.dsms.common.constant.TaskStatusEnum;
import com.dsms.common.constant.TaskTypeEnum;
import com.dsms.common.exception.DsmsEngineException;
import com.dsms.common.taskmanager.TaskStrategy;
import com.dsms.common.taskmanager.model.Task;
import com.dsms.common.taskmanager.service.ITaskService;
import com.dsms.common.util.ByteUtil;
import com.dsms.dfsbroker.rbd.model.Rbd;
import com.dsms.dfsbroker.rbd.model.dto.RbdGetDTO;
import com.dsms.dfsbroker.rbd.model.dto.RbdUpdateDTO;
import com.dsms.dfsbroker.rbd.service.IRbdService;
import com.dsms.dfsbroker.storagepool.model.StoragePool;
import com.dsms.dfsbroker.storagepool.service.IStoragePoolService;
import com.dsms.modules.util.RadosSingleton;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Objects;

@Slf4j
@Service(TaskTypeEnum.TypeConstants.UPDATE_RBD)
public class UpdateRbdTask implements TaskStrategy {
    @Autowired
    private ITaskService taskService;
    @Autowired
    private IStoragePoolService storagePoolService;
    @Lazy
    @Autowired
    private IRbdService rbdService;

    @Override
    public Task execute(Task task) {
        String taskParam = task.getTaskParam();
        if (ObjectUtils.isEmpty(taskParam)) {
            task.setTaskEndTime(LocalDateTime.now());
            task.setTaskStatus(TaskStatusEnum.FAIL.getStatus());
            task.setTaskErrorMessage("task parameter is null");
            return task;
        }
        RbdUpdateDTO rbdUpdateDTO = JSONUtil.toBean(taskParam, RbdUpdateDTO.class);
        StoragePool storagePool;
        Rbd rbd = rbdService.get(new RbdGetDTO(rbdUpdateDTO.getPoolName(), rbdUpdateDTO.getRbdName()));
        if (Objects.isNull(rbd)) {
            throw DsmsEngineException.exceptionWithMessage(ErrorCode.ENOENT.getErrorMessage(), ResultCode.RBD_CREATE_TASK_ERROR);
        }
        if (Objects.equals(rbd.getPoolName(), rbd.getDataPoolName())) {
            storagePool = storagePoolService.get(rbd.getPoolName());
        } else {
            storagePool = storagePoolService.get(rbd.getDataPoolName());
        }
        Rados rados = RadosSingleton.INSTANCE.getRados();
        try (IoCTX ioctx = rados.ioCtxCreate(rbdUpdateDTO.getPoolName());
             RbdImage rbdImage = new com.ceph.rbd.Rbd(ioctx).open(rbdUpdateDTO.getRbdName())) {
            long currentSize = rbdImage.stat().size;
            long rbdAvailableCapacity = storagePool.getRbdAvailableCapacity();
            if (ByteUtil.gbToBytes(rbdUpdateDTO.getRbdSize()) - currentSize > rbdAvailableCapacity) {
                task.setTaskEndTime(LocalDateTime.now());
                task.setTaskErrorMessage("The expansion capacity exceeds the limit");
                task.setTaskStatus(TaskStatusEnum.FAIL.getStatus());
                return task;
            }
            if (ByteUtil.gbToBytes(rbdUpdateDTO.getRbdSize()) <= rbd.getUsedSize()) {
                throw DsmsEngineException.exceptionWithMessage("the capacity of the storage volume cannot be less than the used amount", ResultCode.RBD_CREATE_TASK_ERROR);
            }
            rbdImage.resize(ByteUtil.gbToBytes(rbdUpdateDTO.getRbdSize()));
        } catch (RbdException e) {
            task.setTaskErrorMessage(ErrorCode.getErrorMessage(e.getReturnValue()));
            throw new RuntimeException(ErrorCode.getErrorMessage(e.getReturnValue()));
        } catch (IOException e) {
            task.setTaskErrorMessage(e.getMessage());
            throw new RuntimeException(e);
        } finally {
            task.setTaskStatus(TaskStatusEnum.FAIL.getStatus());
            task.setTaskEndTime(LocalDateTime.now());
        }
        task.setTaskStatus(TaskStatusEnum.FINISH.getStatus());
        task.setTaskEndTime(LocalDateTime.now());
        return task;
    }

    @Override
    public boolean validateTask(String[] validateParam) {
        return taskService.validateTaskMessageAndTaskType(validateParam[0]);
    }
}
